package com._bytecode.__cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {

//    private Object target;

    /**
     * 获得代理对象-1
     * @param target
     * @return
     */
    public Object getProxyInstance(Object target){
//        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        //回调方法
        enhancer.setCallback(this);
        //创建代理对象
        return enhancer.create();
    }

    /**
     * 获得代理对象-2
     * @param clazz
     * @return
     */
    public Object getProxyInstance(Class clazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        //回调方法
        enhancer.setCallback(this);
//        enhancer.setUseCache(true);
        //创建代理对象
        return enhancer.create();
    }


    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("before..");
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("after..");
        return result;
    }
}
